<template>
  <el-row>
    <el-dialog title="详情" :visible="describeTableShow" width="30%" :before-close="() => { describeTableShow = false }">
      <el-table
        :data="describeTableList"
        border
        style="width: 100%"
      >
        <el-table-column
          v-for="item in describeTableColumns"
          :key="item.label"
          :label="item.label"
          :prop="item.name"
        />
      </el-table>
    </el-dialog>

    <el-dialog
      title="创建新会话"
      :visible="inception"
      width="30%"
      :before-close="() => { inception = false }"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" label-position="left">
        <el-form-item label="名称：" prop="session">
          <el-input v-model="form.session" placeholder="请输入名称" style="width: 260px"/>
        </el-form-item>
        <el-form-item label="是否远程：" prop="useRemote">
          <el-switch
            v-model="form.useRemote"
            active-text="开启远程"
            inactive-text="关闭远程"
          />
        </el-form-item>
        <el-form-item label="集群：" prop="clusterId">
          <el-select
            v-model="form.clusterId"
            clearable
            placeholder="请选择分组"
          >
            <el-option
              v-for="item in taskData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addConversation">
            保存
          </el-button>
          <el-button @click="inception = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-switch
      v-model="openClose"
      inactive-text="开启会话："
    />
    <el-button style="margin-left: 20px" type="primary" size="mini" @click="inception = true">
      新增会话
    </el-button>

    <div v-if="openClose" class="tabBox">
      <div class="table1">
        <el-row style="margin: 10px 0">
          <span class="text-subtitle">会话列表</span>
          <el-button
            size="mini"
            type="primary"
            @click="getSessionPageFn"
          >
            刷新
          </el-button>
        </el-row>
        <el-table
          :data="list"
          border
          style="width: 100%"
        >
          <el-table-column
            v-for="item in columns"
            :key="item.label"
            :label="item.label"
            :prop="item.name"
          />
          <el-table-column
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="primary"
                @click="
                  taskParams.useSession && taskParams.session === scope.row.session
                    ? onBreak(scope)
                    : onConnect(scope)"
              >
                {{ taskParams.useSession && taskParams.session === scope.row.session ? '断开' : '连接' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="onDeleteConversation(scope.row.session)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="table2">
        <el-row style="margin: 10px 0">
          <span class="text-subtitle">{{ currentSession }}会话已创建表</span>
          <el-button
            size="mini"
            type="primary"
            @click="getSessionTableFn(currentSession)"
          >
            刷新
          </el-button>
        </el-row>
        <el-table
          :data="list2"
          border
          style="width: 100%"
        >
          <el-table-column
            v-for="item in columns2"
            :key="item.label"
            :label="item.label"
            :prop="item.name"
          />
          <el-table-column
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="primary"
                @click="describeTableFn(scope.row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="onDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-row>
</template>
<script>
// import moment from 'moment'
import { createSession, getSessionPage, deleteSession, getSessionTables, getTableDesc, deleteTable, queryTaskParams } from '../api/workDevelopment'

export default {
  name: 'Conversation',
  props: {
    taskParams: { type: Object, default: () => ({}) }
  },
  data() {
    const selections = []
    const selections2 = []
    const taskData = []
    const describeTableList = []
    const openClose = false
    const orders = [{ column: 'fupdateTime', sorting: 'desc' }]
    // const formDataRules = createQFormRules({
    //   session: [{ required: true, message: '请输入会话名称' }],
    //   clusterId: [{ required: true, message: '请选择集群' }]
    // })
    return {
      form: {
        session: '',
        useRemote: true,
        clusterId: ''
      },
      rules: [],
      // formDataRules,
      describeTableList,
      openClose,
      taskData,
      orders,
      inception: false,
      secondDialog: false,
      list: [],
      list2: [],
      selections,
      selections2,
      describeTableColumns: [
        { name: 'name', label: '名称' },
        { name: 'type', label: '类型' },
        { name: 'null', label: '是否为空' }
      ],
      columns: [
        { name: 'session', label: '会话名称' },
        {
          name: 'useRemote',
          label: '执行模式'
        },
        { name: 'clusterName', label: '集群名' }
      ],
      columns2: [
        { name: 'table name', label: '表名', field: 'table name', align: 'center' },
        { name: '$operate', label: '操作', align: 'center' }
      ],
      loading: false,
      loading2: false,
      filterLock: false,
      describeTableShow: false,
      currentSession: ''
    }
  },
  watch: {
    inception(cur, prev) {
      if (cur && this.taskData.length === 0) {
        this.queryTaskParamsHandle(this.taskParams.taskId)
        this.form.session = ''
        this.form.useRemote = true
        this.form.clusterId = ''
      }
    }
  },
  // created() {
  activated() {
    // this.getList()
    this.getSessionPageFn()
  },

  methods: {
    async getSessionPageFn() {
      console.log('this.taskParams', this.taskParams)
      const res = await getSessionPage()
      this.list = res.map((item) => {
        return {
          ...item,
          useRemote: item.sessionConfig && item.sessionConfig.useRemote ? '远程' : '本地',
          clusterName: item.sessionConfig.clusterName && item.sessionConfig.clusterName ? item.sessionConfig.clusterName : '暂无'
        }
      })
      if (this.taskParams.useSession && this.taskParams.session) {
        this.getList2(this.taskParams.session)
      }
    },
    async getSessionTableFn(sessionName) {
      const res = await getSessionTables({ sessionName })
      console.log('res=======', res)
      this.list2 = res.rowData
    },
    describeTableFn(table) {
      console.log(table)
      const params = {
        sessionName: this.currentSession,
        table: table['table name']
      }
      getTableDesc(params).then((data) => {
        this.describeTableList = data.rowData
        this.describeTableShow = true
      })
    },
    // 会话连接
    onConnect(row) {
      this.taskParams.clusterId = row.row.sessionConfig.clusterId
      this.taskParams.session = row.row.session
      this.taskParams.useRemote = true
      this.taskParams.useSession = true
      this.currentSession = row.row.session
      this.notifySuccess('连接成功')
      this.$emit('changeTaskParams', this.taskParams)
      this.getSessionTableFn(row.row.session)
    },

    // 会话断开
    onBreak(row) {
      this.taskParams.clusterId = row.row.sessionConfig.clusterId
      this.taskParams.session = ''
      this.taskParams.useRemote = true
      this.taskParams.useSession = false
      this.notifySuccess('断开成功')
      this.list2 = []
      this.currentSession = ''
      this.$emit('changeTaskParams', this.taskParams)
    },
    // 点击行
    rowClick(evt, row, index) {
      this.currentSession = row.session
      if (this.taskParams.useSession && this.taskParams.session) {
        this.getList2(row.session)
      }
    },
    // 添加会话
    addConversation() {
      this.$refs['form'].validate(async(valid) => {
        if (!valid) { return false } else {
          await createSession(this.form)
          this.inception = false
          this.notifySuccess('会话新建成功')
          this.getSessionPageFn()
        }
      })
    },
    // 查群集群列表
    async queryTaskParamsHandle(id) {
      console.log(this.taskParams)
      const res = await queryTaskParams({
        taskId: id
      })
      console.log('res===', res)
      this.taskData = res.clusterInStanceData.map((item) => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 获取会话列表
    getList() {
      if (this.loading) {
        return
      }

      this.loading = true
      this.selections = []
      // Service.sessionList(buildQuery(this.pagination, { ...this.filterModel }))
      //   .then((data) => {
      //     if (data && data.code === 200) {
      //       this.list = data.data
      //       this.pagination.rowsNumber = data.data.total
      //       TablePagination.updateTotalPages(this.pagination)
      //       // console.log(data.data);
      //       // this.currentSession = '';
      //       // this.list2 = [];
      //       // data.data.length > 0 ? this.getList2(data.data[0].session) : null;
      //       if (this.taskParams.useSession && this.taskParams.session) {
      //         this.getList2(this.taskParams.session)
      //       }
      //     } else {
      //       this.notifyFailure(data.message ? data.message : data.msg ? data.msg : '会话列表获取失败')
      //       this.loading = false
      //     }
      //   })
      //   .finally(() => (this.loading = false))
    },
    // 获取会话已创建表
    getList2(sessionName) {
      if (this.loading2) {
        return
      }
      this.loading2 = true
      this.selections = []
      // Service.showTables(sessionName)
      //   .then((data) => {
      //     if (data && data.code === 200) {
      //       this.list2 = data.data.rowData

      //       console.log(data.data.rowData)
      //       this.pagination2.rowsNumber = data.data.total
      //       TablePagination.updateTotalPages(this.pagination2)
      //     } else {
      //       this.notifyFailure(data.message ? data.message : data.msg ? data.msg : '会话已创建列表获取失败')
      //       this.loading2 = false
      //     }
      //   })
      //   .finally(() => (this.loading2 = false))
    },

    // 删除会话
    onDeleteConversation(sessionName) {
      this.$q
        .dialog({
          title: '删除会话',
          message: '您确定删除该会话吗？',
          color: 'negative',
          cancel: true
        })
        .onOk(() => {
          deleteSession({ sessionName }).then((data) => {
            if (data) {
              this.notifySuccess('删除成功')
              this.getSessionPageFn()
            } else {
              this.notifyFailure('删除失败')
            }
          })
        })
    },
    onDelete(row) {
      const params = {
        sessionName: this.currentSession,
        table: row['table name']
      }
      this.$q
        .dialog({
          title: '删除会话',
          message: '您确定删除该表吗？',
          color: 'negative',
          cancel: true
        })
        .onOk(() => {
          deleteTable(params)
          this.notifySuccess('删除成功')
          this.getSessionTableFn(this.currentSession)
        })
    },
    /** 响应表格 `@request` 事件 */
    onTableRequest(payload) {
      // TablePagination.updateByRequestPayload(this.pagination, payload)
      this.getList()
    },
    /** 响应表格 `@request` 事件 */
    onTableRequest2(payload) {
      // TablePagination.updateByRequestPayload(this.pagination2, payload)
      this.getList2()
    },
    /** 编辑数据 */
    onEdit(id, ftype) {
      this.$emit('goto', 'info', id, 'EDIT', ftype)
    },

    /** 触发表格请求 */
    triggerTableRequest2() {
      this.$refs.dataTableRef2.requestServerInteraction()
    },
    notifySuccess(text) {
      console.log('F?DS?F?DSF?SD?FSD?F?????')
      this.$q.notify({ type: 'positive', position: 'top', message: text })
    },
    notifyFailure(text) {
      this.$q.notify({ type: 'negative', position: 'top', message: text })
    }
  }
}
</script>
<style lang="scss" scoped>
.tabBox {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .table1 {
    width: 65%;
  }
  .table2 {
    width: 30%;
  }
  .text-subtitle{
    margin-right: 10px;
    font-size: 15px;
    font-weight: 600;
  }
}
</style>
